package org.bao.pet.tools;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.bao.pet.image.ImageReader;
import org.bao.pet.utils.FileSystem;
import org.bao.pet.utils.PlatformInfo;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class Watermarker {
	//public static final String WATERMARK_FILE_DEFAULT = "C:\\watermark.jpg";
	
	private String filepath = null;
	private Image image = null;
	private Image watermark = null;
	private int originalHeight = 0;
	private int originalWidth = 0;
	private int wmHeight = 0;
	private int wmWidth = 0;
	
	public void config(String filepath){
		this.filepath = filepath;
		ImageReader ir = new ImageReader(this.filepath);
		
		this.image = ir.getImage();
		this.originalHeight = this.image.getHeight(null);
		this.originalWidth = this.image.getWidth(null);
		
		
		ir = new ImageReader(PlatformInfo.getInstance().get(PlatformInfo.INFO_TYPE_WATERMARK));
		this.watermark = ir.getImage();
		this.wmHeight = this.watermark.getHeight(null);
		this.wmWidth = this.watermark.getWidth(null);
	}
	
	public void add(){
		BufferedImage bi = new BufferedImage(this.originalWidth,this.originalHeight,BufferedImage.TYPE_INT_RGB);
		Graphics g = bi.createGraphics();
		
		g.drawImage(this.image,0,0,this.originalWidth,this.originalHeight,null);
		
		
		//add water mark.
		g.drawImage(this.watermark, this.originalWidth - this.wmWidth, this.originalHeight - this.wmHeight, this.wmWidth, this.wmHeight,null);
		g.dispose();
		
		File parent = FileSystem.createDirectory(new File(FileSystem.getUpperDirectory(this.filepath)), FileSystem.NEW_DIRECTORY_NAME_DEFAULT);
		String newFilepath = parent + PlatformInfo.getInstance().get(PlatformInfo.INFO_TYPE_SEPARATOR) + FileSystem.generateNewFileName(this.filepath);
		
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(newFilepath);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
			
			encoder.encode(bi);
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ImageFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
